項目根目錄下創建 .github/workflows
ci-cd-pipeline.yml
name: CI/CD Pipeline
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run tests
run: |
pytest
- name: Build Docker image
run: |
docker build -t your-dockerhub-username/your-image-name:latest .
- name: Push Docker image
run: |
echo ${{ secrets.DOCKER_PASSWORD }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin
docker push your-dockerhub-username/your-image-name:latest
- name: Deploy to Docker Swarm
run: |
ssh user@your-server "docker stack deploy -c docker-compose.yml your-stack-name"
Docker Swarm集群設置
在主要伺服器上初始化Swarm
docker swarm init
添加其他節點到Swarm集群
docker swarm join --token <token> <manager-ip>:<port>
創建一個 docker-compose.yml 文件,定義服務、網絡和卷
version: '3.8'
services:
web:
image: your-dockerhub-username/your-image-name:latest
ports:
- "80:80"
deploy:
replicas: 3
update_config:
parallelism: 2
delay: 10s
restart_policy:
condition: on-failure
這一系列步驟確保了應用從代碼提交到自動部署的全過程都能自動化,並且應用能夠在Docker Swarm中穩定運行